package com.zretc.controller;

import com.aliyuncs.exceptions.ClientException;
import com.zretc.entity.User;
import com.zretc.service.UserService;
import com.zretc.util.AliSMSUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @RequestMapping("/login")
    public @ResponseBody boolean login(@RequestParam(value = "userPhone") String userPhone,
                                       HttpSession session){


        User user = userService.getUseruserAccountAndPassword(userPhone);

        if (user == null){
            return false;
        }else{
            // 将用户信息存储session会话中
            session.setAttribute("user",user);
        }
        return true;
    }

    @RequestMapping("/findId")
    @ResponseBody
    public Integer findId(@RequestParam(value = "userPhone") String userPhone){

        User user = userService.getUseruserAccountAndPassword(userPhone);

        return user.getUserId();
    }

    /**
     * 注册
     * @param userPhone
     * @return
     */
    @RequestMapping("/insertUser")
    @ResponseBody
    public boolean insertUser(String userPhone,HttpSession session){
        int n =userService.userInsertRegister(userPhone);
        if (n > 0) {
            User user = userService.getUseruserAccountAndPassword(userPhone);
            // 将用户信息存储session会话中
            session.setAttribute("user",user);
            return true;
        }
        return false;
    }


    /**
     * 更新
     * @param user
     * @return
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public boolean updateUser(User user){
        int n =userService.update(user);
        if (n > 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取手机验证码
     * @param phone
     * @return
     */
    @RequestMapping("/phoneCode")
    @ResponseBody
    public String phoneCode(String phone) throws ClientException {




        String code = AliSMSUtil.sendCode(phone);

        return code;

    }
}
